<template>
  <div>
    <!-- 新增与搜索区域 -->
    <div class="header-actions">
      <el-button @click="showAddDialog">新增题库</el-button>
      <el-input v-model="searchQuery" placeholder="搜索题库..." style="width: 200px;" />
    </div>

    <!-- 添加表格容器ref -->
    <div ref="tableContainer">
      <el-table :data="filteredBanks" border style="width: 100%">
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="name" label="题库名称"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column prop="questionCount" label="题目数量"></el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="editBank(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteBank(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <!-- 新增对话框 -->
    <el-dialog v-model="dialogVisible" title="新增题库" style="width: 500px;">
      <el-form :model="newForm" label-width="100px">
        <el-form-item label="题库名称">
          <el-input v-model="newForm.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">确定新增</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="editDialogVisible" title="编辑题库" style="width: 500px;">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="题库名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import api from '../services/api';
import { ElLoading, ElMessageBox, ElMessage } from 'element-plus';

const banks = ref([]);
const searchQuery = ref('');
const dialogVisible = ref(false);
const newForm = ref({
  name: '',
  description: '',
  createTime: new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString()
});
const editDialogVisible = ref(false);
const editForm = ref({
  id: '',
  name: '',
  description: '',
});

// 过滤后的数据（根据搜索关键词）
const filteredBanks = computed(() => {
  if (!searchQuery.value.trim()) return banks.value;
  const keyword = searchQuery.value.toLowerCase();
  return banks.value.filter(bank =>
    bank.name.toLowerCase().includes(keyword) ||
    (bank.description && bank.description.toLowerCase().includes(keyword))
  );
});

async function fetchBanks() {
  const res = await api.getAllBanks();
  banks.value = res.data;
}

async function submitAdd() {
  try {
    await api.createBank(newForm.value);
    dialogVisible.value = false;
    newForm.value = { name: '', description: '', createTime: new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString(), };
    await fetchBanks();
    ElMessage.success('新增题库成功');
  } catch (error) {
    console.error('新增失败:', error);
    ElMessage.error('新增题库失败');
  }
}

function showAddDialog() {
  dialogVisible.value = true;
}

async function deleteBank(id) {
  try {
    await ElMessageBox.confirm('确定删除该题库？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await api.deleteBank(id);
    await fetchBanks();
    ElMessage.success('删除题库成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除题库失败');
    }
  }
}

function editBank(row) {
  // 复制当前行数据到 editForm 并弹出编辑对话框
  editForm.value = { ...row };
  editDialogVisible.value = true;
}

async function submitEdit() {
  try {
    await api.updateBank(editForm.value);
    editDialogVisible.value = false;
    await fetchBanks();
    ElMessage.success('修改题库成功');
  } catch (error) {
    console.error('编辑失败:', error);
    ElMessage.error('修改题库失败');
  }
}

function formatTime(timeStr) {
  const date = new Date(timeStr);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

const tableContainer = ref(null);  // 添加表格容器ref

onMounted(async () => {
  const loading = ElLoading.service({
    lock: false,
    target: tableContainer.value,
    text: '数据加载中',
    background: 'rgba(0, 0, 0, 0.3)'
  });

  try {
    await fetchBanks();
    setTimeout(() => loading.close(), 500);
  } catch (error) {
    loading.close();
    console.error('初始化数据失败:', error);
  }
});
</script>
<style>
.header-actions {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
  align-items: center;
}
</style>